<template>
  <div>
    <div id="chart-container">
      <div>
        <h3>Mass Fraction_Fe vs. Distance</h3>
        <line-chart
          v-if="chartDataFe"
          :chart-data="chartDataFe"
          :options="chartOptions('Mass Fraction_Fe')"
        />
      </div>
      <div>
        <h3>Mass Fraction_Al vs. Distance</h3>
        <line-chart
          v-if="chartDataAl"
          :chart-data="chartDataAl"
          :options="chartOptions('Mass Fraction_Al')"
        />
      </div>
    </div>
  </div>
</template>

<script>
import * as d3 from 'd3'
import { Line as LineChart } from 'vue-chartjs'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js'

// 注册 ChartJS 组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
)

export default {
  name: 'left_chart',
  components: {
    LineChart
  },
  props: {
    parameters: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      filePath: '',
      csvData: null,
      chartDataFe: null,
      chartDataAl: null
    }
  },
  watch: {
    parameters: {
      immediate: true,
      handler (newParams) {
        if (
          newParams.alloySystem &&
          newParams.elementContent &&
          newParams.temperature &&
          newParams.time
        ) {
          this.generateFilePath(newParams)
        } else {
          this.filePath = ''
          this.csvData = null
          this.chartDataFe = null
          this.chartDataAl = null
        }
      }
    }
  },
  methods: {
    generateFilePath ({ alloySystem, elementContent, temperature, time }) {
      const element = alloySystem.split('x')[1]
      const baseDir = '/public/raw/threechart/Fe'
      const subDir = `${baseDir}/${element}`
      const fileName = `${element}_${temperature}_${element}_${elementContent}_${time}.csv`
      this.filePath = `${subDir}/${fileName}`
      this.readFile()
    },
    async readFile () {
      try {
        const response = await fetch(this.filePath)
        if (response.ok) {
          const rawData = await response.text()
          this.parseCSV(rawData)
        } else {
          console.error(`文件未找到: ${this.filePath}`)
        }
      } catch (error) {
        console.error(`读取文件时出错: ${error.message}`)
      }
    },
    parseCSV (data) {
      const parsedData = d3.csvParse(data)
      this.csvData = parsedData
      this.updateChartData()
    },
    updateChartData () {
      if (!this.csvData) {
        console.error('无CSV数据可用')
        return
      }

      const distances = this.csvData.map((d) => +d.Distance)
      const massFractionFe = this.csvData.map((d) => +d['Mass Fraction_Fe'])
      const massFractionAl = this.csvData.map((d) => +d['Mass Fraction_Al'])

      // 更新 Fe 图表数据
      this.chartDataFe = {
        labels: distances,
        datasets: [
          {
            label: 'Mass Fraction_Fe',
            data: massFractionFe,
            fill: false,
            borderColor: '#2563eb', // 蓝色
            tension: 0.1
          }
        ]
      }

      // 更新 Al 图表数据
      this.chartDataAl = {
        labels: distances,
        datasets: [
          {
            label: 'Mass Fraction_Al',
            data: massFractionAl,
            fill: false,
            borderColor: '#dc2626', // 红色
            tension: 0.1
          }
        ]
      }
    },
    chartOptions (yLabel) {
      return {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: true
          },
          tooltip: {
            mode: 'index',
            intersect: false
          }
        },
        scales: {
          x: {
            title: {
              display: true,
              text: 'Distance'
            }
          },
          y: {
            title: {
              display: true,
              text: yLabel
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped>
#chart-container {
  display: flex;
  justify-content: space-around;
  gap: 20px;
}
#chart-container > div {
  flex: 1;
  height: 400px;
}
</style>
